/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { RuleListUtil } from '../../utils/common/DefectsList';
import { ArkAssignStmt, ArkInstanceInvokeExpr, ArkInvokeStmt, ArkMethod, ArkNormalBinopExpr, Constant, Stmt } from 'arkanalyzer';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { Defects, Rule } from '../../Index';
import { IssueReport } from '../../model/Defects';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { StmtMatcher, MatcherCallback, MatcherTypes } from '../../matcher/Matchers';


const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ImmersiveEffectCheck');
const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: 'docs/immersive-effect-check.md',
    description: 'Call the setWindowLayoutFullScreen() API to extend the UI elements to the status bar and navigation area. Then, call the getWindowAvoidArea() and on(\'avoidAreaChange\') APIs to obtain and dynamically listen for the change information about the avoid area, based on which the page layout is dynamically adjusted.',
};

export class ImmersiveEffectCheck implements BaseChecker {
  readonly metaData: BaseMetaData = gMetaData;
  public rule: Rule;
  public defects: Defects[] = [];
  public issues: IssueReport[] = [];

  private stmtMatcher: StmtMatcher = {
    matcherType: MatcherTypes.STMT,
    match(stmt: Stmt): boolean {
      return stmt instanceof ArkAssignStmt;
    },
  };

  public registerMatchers(): MatcherCallback[] {
    const matchStmtCb: MatcherCallback = {
      matcher: this.stmtMatcher,
      callback: this.check,
    };
    return [matchStmtCb];
    }

  public check = (stmt: ArkAssignStmt): void => {
    const rightOp = stmt.getRightOp();
    if (!(rightOp instanceof ArkInstanceInvokeExpr)) {
      return;
    }
    const methodName = rightOp.getMethodSignature().getMethodSubSignature().getMethodName();
    if (methodName === 'setWindowLayoutFullScreen') {
      this.checkInside(stmt);
    }
  };

  private checkInside(stmt: ArkAssignStmt): void {
    const blocks = stmt.getCfg()?.getBlocks();
    if (!blocks) {
      return;
    }
    let hasGetWindowAvoidArea = false;
    let hasOnAvoidAreaChange = false;
    for (const block of blocks) {
      const stmts = block.getStmts();
      for (const currentStmt of stmts) {
        if (!hasGetWindowAvoidArea && currentStmt instanceof ArkAssignStmt) {
          hasGetWindowAvoidArea = this.checkArkAssignStmt(currentStmt);
        } else if (!hasOnAvoidAreaChange && currentStmt instanceof ArkInvokeStmt) {
          hasOnAvoidAreaChange = this.checkArkInvokeStmt(currentStmt);
        }
        if (hasGetWindowAvoidArea && hasOnAvoidAreaChange) {
          return;
        }
      }
    }
    if (!(hasGetWindowAvoidArea && hasOnAvoidAreaChange)) {
      this.addIssueReport(stmt, 'There is a blank space issue in the bottom navigation or top status bar.');
    }
  }

  private checkArkAssignStmt(stmt: ArkAssignStmt): boolean {
    const rightOp = stmt.getRightOp();
    if (rightOp instanceof ArkInstanceInvokeExpr) {
      const methodName = rightOp.getMethodSignature().getMethodSubSignature().getMethodName();
      if (methodName === 'getWindowAvoidArea') {
        return true;
      }
    }
    return false;
  }

  private checkArkInvokeStmt(stmt: ArkInvokeStmt): boolean {
    const invokeExpr = stmt.getInvokeExpr();
    const arg1 = invokeExpr.getArg(0);
    if (arg1 instanceof Constant && arg1.getValue() === 'avoidAreaChange') {
      const methodName = invokeExpr.getMethodSignature().getMethodSubSignature().getMethodName();
      if (methodName === 'on') {
        return true;
      }
    }
    return false;
  }

  private addIssueReport(stmt: ArkAssignStmt, message: string): void {
    const severity = this.rule.alert ?? this.metaData.severity;
    let lineAndColLocation = stmt.getOriginPositionInfo();
    const arkFile = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile();
    let textLength = 0;
    if (stmt !== undefined && stmt.getOriginalText() !== undefined) {
      textLength = stmt.getOriginalText()?.length ?? 0;
    }
    let endCol = lineAndColLocation.getColNo() + textLength;
    let defects = new Defects(lineAndColLocation.getLineNo(), lineAndColLocation.getColNo(), endCol,
      message, severity, this.rule.ruleId, arkFile.getFilePath(), this.metaData.ruleDocPath, true, false, true);
    this.issues.push(new IssueReport(defects, undefined));
    RuleListUtil.push(defects);
  }
}